# -*- coding: utf-8 -*-
from tornado import gen
from common import timetool
from qcmodule import push
from settings import mysql_app_pool


@gen.coroutine
def get_bmt_list(device_type, area):
    current_time = timetool.get_timestamp()
    sql = (
        "select b.client_id from couch_bmt a LEFT JOIN app_clientids b "
        "on a.phone = b.phone "
        "LEFT JOIN couch_driver_addr c "
        "on a.phone = c.phone  "
        "where a.end > {} "
        "and b.device_type = {} "
        u"and c.area = '{}'"
    )
    info = yield mysql_app_pool.get_all(sql.format(current_time, device_type, area), cursor='dict')
    raise gen.Return(info)


@gen.coroutine
def get_push_info_pub_consult(info_id):
    sql = (
        "select a.*, b.avatar, b.nick_name from pub_consult a LEFT JOIN app_user_info b "
        "on a.phone = b.phone "
        "where a.id = {}"
    )
    info = yield mysql_app_pool.get_one(sql.format(info_id), cursor='dict')
    raise gen.Return(info)


@gen.coroutine
def get_push_info_consult(info_id):
    sql = (
        "select a.*, b.client_id, c.nick_name, c.avatar from student_consult a, app_clientids b, app_user_info c "
        "where a.id = {} "
        "and a.couch_phone = b.phone "
        "and a.phone = c.phone"
    )
    info = yield mysql_app_pool.get_one(sql.format(info_id), cursor='dict')
    raise gen.Return(info)


@gen.coroutine
def deal_push_pub_consult():
    # 6
    start_time = timetool.get_timestamp()
    sql = "select * from app_push_task where status = 0 and type=6 order by id limit 50"
    res = yield mysql_app_pool.get_all(sql, cursor='dict')
    if res:
        sql_1 = "update app_push_task set status = 1, start_time={} where type=6 and id BETWEEN {} and {};"
        yield mysql_app_pool.update(sql_1.format(start_time, res[0]['id'], res[-1]['id']))
        for item in res:
            push_info = yield get_push_info_pub_consult(item['info_id'])
            if not push_info:
                continue
            push_info['push_type'] = item['type']
            print push_info
            info_dict = dict(
                content=push_info,
                title=u"收到一条一键咨询信息",
                text=""
            )
            ios_bmt_list = yield get_bmt_list(1, push_info['area'])
            android_bmt_list = yield get_bmt_list(0, push_info['area'])
            ios_res = yield push.push_message_to_list(info_dict, 1, ios_bmt_list)
            android_res = yield push.push_message_to_list(info_dict, 0, android_bmt_list)
            print ios_res
            print android_res
            end_time = timetool.get_timestamp()
            if ios_res['result'] == 'ok' and android_res['result'] == 'ok':
                sql_2 = "update app_push_task set status = 2, push_status='{}',end_time={} where id = {};"
                yield mysql_app_pool.update(sql_2.format('success', end_time, item['id']))
            else:
                sql_3 = "update app_push_task set status = 3, push_status='{}',end_time={} where id = {};"
                yield mysql_app_pool.update(sql_3.format('fail', end_time, item['id']))
    else:
        print 'pub consult nothing to do....'


@gen.coroutine
def deal_push_consult():
    # 5
    start_time = timetool.get_timestamp()
    sql = "select * from app_push_task where status = 0 and type=5 order by id limit 10"
    res = yield mysql_app_pool.get_all(sql, cursor='dict')
    if res:
        sql_1 = "update app_push_task set status = 1, start_time={} where type=5 and id BETWEEN {} and {};"
        yield mysql_app_pool.update(sql_1.format(start_time, res[0]['id'], res[-1]['id']))
        for item in res:
            push_info = yield get_push_info_consult(item['info_id'])
            if not push_info:
                continue
            push_info['push_type'] = item['type']
            print push_info
            info_dict = dict(
                content=push_info,
                title=u"收到一条咨询信息",
                text=""
            )
            push_res = yield push.push_message_to_single(info_dict, push_info['client_id'])
            end_time = timetool.get_timestamp()
            if push_res['result'] == 'ok':
                sql_2 = "update app_push_task set status = 2, push_status='{}',end_time={} where id = {};"
                yield mysql_app_pool.update(sql_2.format('success', end_time, item['id']))
            else:
                sql_3 = "update app_push_task set status = 3, push_status='{}',end_time={} where id = {};"
                yield mysql_app_pool.update(sql_3.format('fail', end_time, item['id']))
    else:
        print 'consult nothing to do....'
